package com.csw.android.androidtest.module.webview;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.csw.android.androidtest.R;
import com.csw.android.dev_utils.ui.BaseFragment;
import com.csw.android.dev_utils.utils.LogUtils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class WebViewTest extends BaseFragment {
    private WebView webView;

    @Override
    public int getContentViewID() {
        return R.layout.fragment_web_view_test;
    }

    @Override
    public void initView(@NotNull View rootView, @Nullable Bundle savedInstanceState) {
        super.initView(rootView, savedInstanceState);
        webView = rootView.findViewById(R.id.webView);
        settingWebView(webView);
        webView.loadUrl("http://zyxx.zhongyuedu.com/bencandy.php?fid=523&aid=14185");
    }

    private void settingWebView(WebView webView) {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                LogUtils.INSTANCE.d(WebViewTest.this, "onLoadResource_>" + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LogUtils.INSTANCE.d(WebViewTest.this, "onPageFinished_>" + url);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                LogUtils.INSTANCE.d(WebViewTest.this, "onProgressChanged_>" + newProgress);
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    }

    @Override
    public void onDestroyView() {
        webView.stopLoading();
        webView.destroy();
        webView.clearCache(true);
        ViewParent vp = webView.getParent();
        if (vp instanceof ViewGroup) {
            ((ViewGroup) vp).removeView(webView);
        }
        webView = null;
        super.onDestroyView();
    }
}
